package com.zzw.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Scanner;

public class MybatisCodeGen {
    public static void main(String[] args) {
        //1.创建generator对象
        AutoGenerator autoGenerator = new AutoGenerator();
        //2.配置数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/db_baobao?useSSL=false&useUnicode=true&characterEncoding=utf-8");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        autoGenerator.setDataSource(dataSourceConfig);

        //3.全局配置(指明这些类生成的具体位置以及作者....)
        GlobalConfig globalConfig = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        System.out.println(projectPath);
        globalConfig.setOutputDir(projectPath + "/src/main/java");
        globalConfig.setAuthor(scanner("请输入开发者名字"));
        globalConfig.setOpen(false);//不打开文件
//        globalConfig.setFileOverride(true); 一般不覆盖，有可能文件有自定义修改
        String bswa = scanner("是否开启文档配置Swagger(y/n)");
        if ("y".equalsIgnoreCase(bswa)) {
            globalConfig.setSwagger2(true);
        }
        globalConfig.setEntityName("%sEntity");
        autoGenerator.setGlobalConfig(globalConfig);

        //4.设置包信息(生成的类放在哪个包里面)
        String model = scanner("模块名(如果没有子模块请输入(n))");
        String modelpackage = ("n".equalsIgnoreCase(model)) ? "" : "." + model;
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.zzw.mybatisplustest");
        packageConfig.setEntity("entity" + modelpackage);
        packageConfig.setController("rest.controller" + modelpackage);
        packageConfig.setMapper("mapper" + modelpackage);
        packageConfig.setService("service" + modelpackage);
        packageConfig.setServiceImpl("service.impl" + modelpackage);
        autoGenerator.setPackageInfo(packageConfig);

        //自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                //to do nothing
            }
        };
        ArrayList<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                String mapperpackage = ("n".equalsIgnoreCase(model)) ? "" : model;
                return projectPath + "/src/main/resources/mapper/" + mapperpackage
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        autoGenerator.setCfg(cfg);
        autoGenerator.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setEntityTableFieldAnnotationEnable(true);
        strategyConfig.setRestControllerStyle(true);
        strategyConfig.setInclude("user".toUpperCase());
//        strategyConfig.setSuperEntityColumns("id");
        strategyConfig.setControllerMappingHyphenStyle(true);
        strategyConfig.setTablePrefix(packageConfig.getModuleName() + "_");
        autoGenerator.setStrategy(strategyConfig);
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
        //6.执行
        autoGenerator.execute();
    }

    private static String scanner(String tip) {
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ": ");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }
}
